<?php

/*
 * @see https://leetcode.cn/problems/add-two-numbers/
 */

class ListNode
{
    public $val = 0;
    public $next = null;

    function __construct($val = 0, $next = null)
    {
        $this->val = $val;
        $this->next = $next;
    }
}

class Solution
{
    function build($input)
    {
        $headNode = new ListNode();
        $position = $headNode;

        foreach ($input as $value) {
            $position->next = new ListNode($value);
            $position = $position->next;
        }

        return $headNode->next;
    }

    public function handle(ListNode $list, ListNode $other)
    {
        if (is_null($list) && is_null($other)) return null;

        $headNode = new ListNode();
        $position = $headNode;
        $sign = 0;

        while (!is_null($list) || !is_null($other)) {
            $value = $sign + ($list->val ?? 0) + ($other->val ?? 0);
            if ($value > 9) {
                $value -= 10;
                $sign = 1;
            } else {
                $sign = 0;
            }

            $position->next = new ListNode($value);
            $position = $position->next;

            $list = $list->next ?? null;
            $other = $other->next ?? null;
        }

        if ($sign === 1) {
            $position->next = new ListNode($sign);
        }

        return $headNode->next;
    }
}

$handler = new Solution();
$result = $handler->handle($handler->build([9, 9, 9, 9, 9, 9, 9]), $handler->build([9, 9, 9, 9]));
var_dump($result);
